package com.tencentbridge.swagger3;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author xupt
 */
@Configuration
public class Swagger3Config {

    /**
     * 定义的token名字
     */
    private static final String TOKEN_NAME = "Authorization";

    @Bean
    public Docket createRestApi() {
        //存储用户必须提交的参数
        List<SecurityScheme> apiKeys = Collections.singletonList(HttpAuthenticationScheme.JWT_BEARER_BUILDER
                .name(TOKEN_NAME)
                .build());
        //如果用户JWT认证通过，则在Swagger中全局有效
        AuthorizationScope scope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] scopeArray = {scope};
        //存储令牌和作用域
        SecurityReference reference = new SecurityReference(TOKEN_NAME, scopeArray);
        ArrayList<SecurityReference> referenceArrayList = new ArrayList<>();
        referenceArrayList.add(reference);
        SecurityContext context = SecurityContext.builder().securityReferences(referenceArrayList).build();
        ArrayList<SecurityContext> contextArrayList = new ArrayList<>();
        contextArrayList.add(context);

        return new Docket(DocumentationType.OAS_30)
                //配置api文档元信息
                .apiInfo(apiInfo())
                // 选择哪些接口作为swagger的doc发布
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(apiKeys)
                .securityContexts(contextArrayList);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("改色系统接口文档")
                .description("贴膜改色系统后端接口")
                .contact(new Contact("Xpt", "https://tencentbridge.com", "miniprogram@88.com"))
                .version("1.0")
                .build();
    }
}
